<?php

/**
 * aluno actions.
 *
 * @package    ibe
 * @subpackage aluno
 * @author     Creatix
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class alunoActions extends sfActionsCreatix
{
	public function executeIndex(sfWebRequest $request)
	{
		return $this->forward('aluno', 'list');
	}

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= AlunoTable::consultar($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Url'));

		foreach($this->data as &$r)
		{
			$actions = array(
				'edit'	 => "<a href='".url_for($this->getModuleName().'/edit?id_aluno='.$r['id_aluno'])."' class='icoEditar' title='Editar Aluno'></a>",
	    		'show' => "<a href='".url_for($this->getModuleName().'/show?id_aluno='.$r['id_aluno'])."'  class='icoVisualizar' title='Visualizar Aluno'></a>",
	    		'turma' => "<a href='".url_for($this->getModuleName().'/turmas?id_aluno='.$r['id_aluno'])."' class='icoAdicionar' title='Adicinar na Turma'></a>",
				'delete' => "<a href='".url_for($this->getModuleName().'/delete?id_aluno='.$r['id_aluno'])."'  class='icoExcluir delete' title='Deletar Aluno'></a>",
			);
			$r['act'] = implode(' ', $actions);
		}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


	public function executeList()
	{
		$this->form = new AlunoForm();
		$this->colunas	= array(
		$this->form['id_aluno']->renderLabel() => "id_aluno",
		$this->form['nm_aluno']->renderLabel() => "nm_aluno",
		$this->form['st_aluno']->renderLabel() => "st_aluno",
						"Ações"	=> "act"
						);

						$this->filter = $this->_getFilter();
						$this->setTemplate('index');
	}

	public function executeFilter()
	{
		$filter = new Filtro(
		$this->getRequestParameter(sfActionsCreatix::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
		sfActionsCreatix::FILTER_SESSION_USER_ATTRIBUTE,
		serialize($filter),
		$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

	public function executeShow(sfWebRequest $request)
	{
		$this->aluno = Doctrine::getTable('Aluno')->find(array($request->getParameter('id_aluno')));
		$this->forward404Unless($this->aluno);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new AlunoForm();
		$this->responsavelForm	= new DadosResponsavelForm($this->form->getObject()->DadosResponsavel);
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		$this->form = new AlunoForm();
		return $this->processForm($request, $this->form);
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($aluno = Doctrine::getTable('Aluno')->find(array($request->getParameter('id_aluno'))), sprintf('Object aluno does not exist (%s).', $request->getParameter('id_aluno')));
		$this->form = new AlunoForm($aluno);
		$this->responsavelForm	= new DadosResponsavelForm($this->form->getObject()->DadosResponsavel);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($aluno = Doctrine::getTable('Aluno')->find(array($request->getParameter('id_aluno'))), sprintf('Object aluno does not exist (%s).', $request->getParameter('id_aluno')));
		$this->form = new AlunoForm($aluno);

		return $this->processForm($request, $this->form);
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$this->forward404Unless($aluno = Doctrine::getTable('Aluno')->find(array($request->getParameter('id_aluno'))), sprintf('Object aluno does not exist (%s).', $request->getParameter('id_aluno')));
//			$aluno->delete(); // Nao haverá DELETE de dados
			$aluno->setStAluno('E');
			$aluno->save();

			$this->redirect('aluno/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('aluno/index');
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
				$aluno = $form->save();
			else
				throw new Exception($form->getErrorSchema());
			
			$result = array(
				'id_aluno' => $aluno->getIdAluno()
			);
			
			return $this->outputJson($result);
		}
		catch(Exception $e)
		{
			$result = array('error' => utf8_decode($e->getMessage()));
			return $this->outputJson($result);
		}
	}
	
	public function executeTurmas(sfWebRequest $request)
	{
		$this->aluno = Doctrine::getTable('Aluno')->find(array($request->getParameter('id_aluno')));
		$this->forward404Unless($this->aluno);
		
		if( $request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT) )
		{ // se o formulário foi submetido
			AlunoTurmaTable::vinculaAlunoTurmas($this->aluno, $request->getPostParameter('turma', array()));
			$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
			$this->redirect('aluno/list');
		}

		$this->turmas =  TurmaTable::carregarTurmasDisponiveisAluno($this->aluno);
	}
	
	public function executeSalvarDadosPais(sfWebRequest $request)
	{
		try {
			$aluno = Doctrine::getTable('Aluno')->find($request->getParameter('id_aluno'));
			$form = new AlunoForm($aluno);
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			
			if($form->isValid())
				$aluno = $form->save();
			else 
				throw new Exception($form->getErrorSchema());
				
			$result = array(
				'id_aluno' => $aluno->getIdAluno()
			);
			
			return $this->outputJson($result);
			
		} catch (Exception $e) {
			
			return $this->outputJson(utf8_encode($e->getMessage()));
		}
	}
}
